package projet.ejb;

import java.util.Collection;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import projet.entity.Compte;
import projet.entity.Investisseur;

@Stateless
public class CompteFacadeEJB implements CompteFacade {
	@PersistenceContext(unitName = "SampleUnit")
	protected EntityManager entityMgr;
	
	public Compte add(Compte c) {
		entityMgr.persist(c);
		return c;
	}
	
	public Compte authentification(String login, String password){
		Query query = entityMgr.createQuery("SELECT c FROM  Compte as c WHERE (c.login=:l and c.password=:p) ");
		query.setParameter("l",login);
		query.setParameter("p",password);
		Compte c =   (Compte) query.getSingleResult();
		return c;		
	}
		
	public Compte findByLogin(String login){		
		Query query = entityMgr.createQuery("SELECT c FROM  Compte as c WHERE c.login=:n ");
		query.setParameter("n",login);
		Compte c =   (Compte) query.getSingleResult();
		return c;
	}	
	
	public Compte findByPassword(String password){		
		Query query = entityMgr.createQuery("SELECT c FROM  Compte as c WHERE c.password=:n ");
		query.setParameter("n",password);
		Compte c =   (Compte) query.getSingleResult();
		return c;
	}
	
	@SuppressWarnings("unchecked")
	public Collection<Compte> findAll() {
		 return entityMgr.createQuery("SELECT c FROM Compte as c").getResultList();
	}

	public void deleteAll() {
		Collection<Compte> l_compte = findAll();
		for(Compte c : l_compte){
			entityMgr.remove(c);
		}
	}
	
	public void delete(int id) {
		Compte c = entityMgr.find(Compte.class,id);
			entityMgr.remove(c);
		}

	public Compte updateLogin(int id ,String login){
		Compte l= entityMgr.find(Compte.class, id);
		l.setLogin(login);
		return l;
	}
	
	public Compte updatePassword(int id, String pass){
		Compte l= entityMgr.find(Compte.class, id);
		l.setPassword(pass);
		return l;
	}
}
